<template>
  <a-card :bordered="false">
    <template v-if="this.departId">
      <a-spin :spinning="loading">
        <a-form>
          <a-row>
            <a-col :span="11" style="margin-right:8px">
              <a-form-item>
                <a-card title="应用列表">
                  <a-tree
                    checkable
                    @check="onAppCheck"
                    :treeData="appData"
                    :checkedKeys="checkedAppKeys"
                    @select="onAppSelect"
                    :checkStrictly="checkAppStrictly"
                    :selectedKeys="selectedAppKeys"
                    style="height:500px;overflow: auto;"
                  />
                </a-card>
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <a-form-item>
                <a-card title="所拥有的权限">
                  <a-tree
                    v-if="permissionData.length > 0"
                    checkable
                    :checkedKeys="checkedPermission"
                    :treeData="permissionData"
                    :autoExpandParent="autoExpandParentPermission"
                    :selectedKeys="selectedKeys"
                    @check="onCheckPermission"
                    @select="onTreeNodeSelect"
                    :defaultExpandAll="defaultExpandAll"
                    style="height:500px;overflow: auto;">
                    <span slot="hasDatarule" slot-scope="{slotTitle,ruleFlag}">
                      {{ slotTitle }}<a-icon v-if="ruleFlag" type="align-left" style="margin-left:5px;color: red;"></a-icon>
                    </span>
                  </a-tree>
                </a-card>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
      <div class="anty-form-btn">
        <!-- <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
          <a-menu slot="overlay">
             简化Tree逻辑，使用默认checkStrictly为false的行为，即默认父子关联
            <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
            <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>

            <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作 <a-icon type="up" />
          </a-button>
        </a-dropdown> -->
        <a-button style="float: right" @click="handleSubmit" type="primary" htmlType="button" icon="form">保存</a-button>
      </div>
    </template>
    <a-card v-else :bordered="false" style="height:200px">
      <a-empty>
        <span slot="description"> 请先选择一个部门! </span>
      </a-empty>
    </a-card>
    <depart-datarule-modal ref="datarule"/>
  </a-card>
</template>

<script>
  import DepartDataruleModal from './modules/DepartDataruleModal.vue'
  import { removeArray } from '@/utils/util.js'
  import { queryDepartAppTree, saveDepartPermission, queryDepartAppPermission } from './service';
  import { queryTenantRoleAppTree } from '@views/system/role/service';

  export default {
    name: 'DepartAuthModal',
    components: { DepartDataruleModal },
    data() {
      return {
        departId: '',
        defaultCheckedKeys: [],
        expandedKeysss: [],
        defaultExpandAll: true,
        autoExpandParent: true,
        checkStrictly: false,
        title: '部门权限配置',
        visible: false,
        loading: false,

        /** 应用列表 */
        appData: [],
        checkedAppKeys: [],
        selectedAppKeys: [],
        checkAppStrictly: false,
        delAppkeys: [], // 删除的AppKey

        /** 应用权限 */
        permissionData: [],
        checkedPermission: [],
        selectedKeys: [],
        autoExpandParentPermission: true,
        allTreeKeys: [],
        halfCheckedKeys: [],

        appPermissionMap: new Map(),
        selectedApp: {},
        requestedAppIds: []
      }
    },
    methods: {
      onTreeNodeSelect(id) {
        if (id && id.length > 0) {
          this.selectedKeys = id
        }
        this.$refs.datarule.show(this.selectedKeys[0], this.departId)
      },
      // onCheck (checkedKeys, { halfCheckedKeys }) {
      //   // 保存选中的和半选中的，后面保存的时候合并提交
      //   this.checkedKeys = checkedKeys
      //   this.halfCheckedKeys = halfCheckedKeys
      // },
      show(departId, tenantId) {
        this.departId = departId
        this.tenantId = tenantId;
        this.reset();
        this.loadData();
      },
      close () {
        this.reset()
        this.$emit('close');
        this.visible = false;
      },
      onExpand(expandedKeys) {
        this.expandedKeysss = expandedKeys;
        this.autoExpandParent = false
      },
      reset () {
        this.expandedKeysss = []
        // this.checkedKeys = []
        this.defaultCheckedKeys = []
        this.appData = []
        this.checkedAppKeys = []
        this.selectedAppKeys = []
        this.delAppkeys = []
        this.permissionData = []
        this.checkedPermission = []
        this.selectedKeys = []
        this.allTreeKeys = []
        this.appPermissionMap.clear()
        this.selectedApp = {}
        this.loading = false
        this.requestedAppIds = []
      },
      expandAll () {
        this.expandedKeysss = this.allTreeKeys
      },
      closeAll () {
        this.expandedKeysss = []
      },
      checkALL () {
        this.checkedKeys = this.allTreeKeys
      },
      cancelCheckALL () {
        this.checkedKeys = []
      },
      handleCancel () {
        this.close()
      },
      handleSubmit() {
        let that = this;
        if (!that.departId) {
          this.$message.warning('请点击选择一个部门!')
        }
        let params = {
          tenantId: that.tenantId,
          departId: that.departId,
          roleApps: [],
          delRoleApps: []
        }
         let selectedApp = [];
        // 添加删除的
        if (that.delAppkeys && that.delAppkeys.length > 0) {
            that.delAppkeys.forEach(key => {
              that.appData.forEach(function(roleApp) {
              if (roleApp.key === key) {
                params.delRoleApps.push({ 'roleId': roleApp.roleId, 'appId': roleApp.appId, 'departId': that.departId });
              }
              });
            });
        }
        // 获取已选应用中的列表
         if (that.checkedAppKeys && that.checkedAppKeys.length > 0) {
            that.checkedAppKeys.forEach(function(element) {
              that.appData.forEach(function(roleApp) {
                  if (roleApp.key === element) {
                    selectedApp.push(roleApp);
                  }
              });
            });
          }
          selectedApp.forEach(function(roleApp) {
            let key = roleApp.key;
            let appPermission = that.appPermissionMap.get(key)
            if (appPermission) {
              appPermission.permissionIds = [...appPermission.permissionIds, ...appPermission.halfPermissionIds]
              params.roleApps.push({ 'roleId': roleApp.roleId, 'appId': roleApp.appId, 'departId': that.departId, 'appPermissions': appPermission });
            } else {
              params.roleApps.push({ 'roleId': roleApp.roleId, 'appId': roleApp.appId, 'departId': that.departId });
            }
          });

        that.loading = true;
        console.log('请求参数：', params);
        saveDepartPermission(params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loading = false;
            that.loadData();
          } else {
            that.$message.error(res.message);
            that.loading = false;
          }
        })
      },
      /** 转换 */
      convertTreeListToKeyLeafPairs(treeList, keyLeafPair = []) {
        for (const { key, leaf, children } of treeList) {
          keyLeafPair.push({ key, leaf })
          if (children && children.length > 0) {
            this.convertTreeListToKeyLeafPairs(children, keyLeafPair)
          }
        }
        return keyLeafPair;
      },
      emptyCurrForm() {
        this.form.resetFields()
      },
      loadData() {
        // this.loading = true;
        this.loadAppData();
        // 获取当前选择的
        this.loadPermissionData(this.tenantId, this.selectedApp)
      },

      /** 获取应用对应的权限 */
      loadPermissionData(tenantId, selectedApp) {
        if (selectedApp && Object.keys(selectedApp).length > 0) {
            let params = { };
            if (!selectedApp.roleId) {
              this.permissionData = [];
              this.allTreeKeys = [];
              return;
            }
            queryTenantRoleAppTree(tenantId, selectedApp.roleId, selectedApp.appId, params).then((res) => {
              this.permissionData = res.result.treeList
              this.allTreeKeys = res.result.ids
              const keyLeafPairs = this.convertTreeListToKeyLeafPairs(this.permissionData)
              let isRequested = this.requestedAppIds.findIndex(key => key === selectedApp.appId) !== -1;
              if (isRequested) {
                let permissionIds = this.getPermissionIdsByKey(selectedApp.appId)
                let halfPermissionIds = this.getHalfPermissionsIdsByKey(selectedApp.appId)
                let result = [...permissionIds, ...halfPermissionIds];
                this.parsePermissionResult(keyLeafPairs, result);
                // this.checkedPermission = [...permissionIds];
                // this.halfCheckedKeys = [...halfPermissionIds];
                // this.defaultCheckedKeys = [...permissionIds, ...halfPermissionIds];
                return;
              }
              let params = {
                departId: this.departId,
                appId: selectedApp.appId
              }
              queryDepartAppPermission(selectedApp.appId, params).then((res) => {
                // 请求成功
                if (res.success) {
                  this.requestedAppIds.push(selectedApp.appId);
                   if (res.result && res.result.length > 0) {
                    this.parsePermissionResult(keyLeafPairs, res.result);
                    this.setAppPermission(selectedApp, this.checkedPermission, this.halfCheckedKeys)
                  // console.log(this.appPermissionMap);
                  } else {
                    this.checkedPermission = [];
                    this.halfCheckedKeys = [];
                    this.defaultCheckedKeys = [];
                    this.expandedKeysss = this.allTreeKeys;
                  }
                }
              })
            })
          }
      },
      onCheckPermission (checkedPermission, { halfCheckedKeys }) {
        // 保存选中的和半选中的，后面保存的时候合并提交
        this.checkedPermission = checkedPermission
        this.halfCheckedKeys = halfCheckedKeys
        this.setAppPermission(this.selectedApp, this.checkedPermission, this.halfCheckedKeys)
        // console.log(this.checkedPermission);
        // console.log(this.halfCheckedKeys);
        // console.log(this.appPermissionMap);
      },

      /** 应用列表相关方法 */
       /* **********应用列表************* */
      loadAppData() {
        let params = {
          'tenantId': this.tenantId,
          departId: this.departId
          };
        queryDepartAppTree(params).then((res) => {
          if (res.success) {
            this.appData = [...res.result.appList];
            this.checkedAppKeys = [...res.result.authAppIds];
            this.setAppChecked(this.checkedAppKeys);
            // console.log(this.appPermissionMap);
          } else {
          }
        }).finally(() => {})
      },
       onAppSelect(selectedKeys, e) {
        let that = this;
        this.selectedAppKeys = selectedKeys;
        if (selectedKeys) {
          let selectedApp = {}
          let curKey = selectedKeys[0];
          that.appData.forEach(function (item) {
          if (curKey === item.key) {
              selectedApp = item;
              return true;
            }
          })
          if (selectedApp) {
            that.selectedApp = selectedApp;
            this.loadPermissionData(this.tenantId, that.selectedApp);
           }
        }
      },
       onAppCheck (checkedKeys, e) {
        if (this.checkAppStrictly) {
          this.checkedAppKeys = [].concat(checkedKeys.checked[checkedKeys.checked.length - 1]);
        } else { // 可多选
          this.checkedAppKeys = checkedKeys;
        }
        let appKey = e.node.eventKey;
        // 获取当前点击的appId 即 key
        // 取消
        if (!e.checked) {
          this.delAppkeys.push(appKey);
        } else { // 如果选中 从列表中删除
          removeArray(this.delAppkeys, appKey)
        }
      },
       /** 保存数据集合处理 */
      setAppPermission (selectedApp, pPermissionIds, halfCheckedKeys) {
        let obj = {
          roleId: selectedApp.roleId,
          appId: selectedApp.appId,
          departId: this.departId,
          permissionIds: pPermissionIds,
          halfPermissionIds: halfCheckedKeys
        }
        let key = this.getKey(selectedApp.appId);
        if (this.appPermissionMap.has(key)) {
            this.appPermissionMap.get(key).permissionIds = [...pPermissionIds];
            this.appPermissionMap.get(key).halfPermissionIds = [...halfCheckedKeys];
        } else {
          this.appPermissionMap.set(key, obj);
        }
          // console.log(this.appPermissionMap);
      },
      setAppChecked (checkedAppKeys) {
        if (checkedAppKeys && checkedAppKeys.length > 0) {
          checkedAppKeys.forEach(element => {
            this.appData.forEach(app => {
              if (app.key === element) {
                // 存入map
                if (!this.appPermissionMap.has(element)) {
                  this.setAppPermission(app, [], []);
                }
              }
            });
          });
        }
      },
      getKey(appId) {
        return String(appId);
      },
      // 主要用来处理 再次点击应用列表时，上次选择的丢失问题
      getPermissionIdsByKey(key) {
        let appPermission = this.appPermissionMap.get(key)
        if (appPermission) {
          return appPermission.permissionIds;
        }
        return [];
      },
      getHalfPermissionsIdsByKey(key) {
        let appPermission = this.appPermissionMap.get(key)
        if (appPermission) {
          return appPermission.halfPermissionIds;
        }
        return [];
      },
      parsePermissionResult(keyLeafPairs, result) {
         // 过滤出 leaf node 即可，即选中的
        // Tree组件中checkStrictly默认为false的时候，选中子节点，父节点会自动设置选中或半选中
        // 保存 checkedKeys 以及 halfCheckedKeys 以便于未做任何操作时提交表单数据
        const checkedPermissionKeys = [...result].filter(key => {
          const keyLeafPair = keyLeafPairs.filter(item => String(item.key) === String(key))[0]
          return keyLeafPair && keyLeafPair.leaf
        })
        const halfCheckedPermissionKeys = [...result].filter(key => {
          const keyLeafPair = keyLeafPairs.filter(item => String(item.key) === String(key))[0]
          return keyLeafPair && !keyLeafPair.leaf
        })

        this.checkedPermission = [...checkedPermissionKeys];
        this.halfCheckedKeys = [...halfCheckedPermissionKeys];
        this.defaultCheckedKeys = [...halfCheckedPermissionKeys, ...checkedPermissionKeys];
        this.expandedKeysss = this.allTreeKeys;
      }

    }
  }
</script>

<style scoped>

</style>
